<?php
namespace app\api\controller;

use Think\Db;
use app\common\logic\GoodsLogic;
use app\common\logic\CartLogic;
use app\common\logic\OrderLogic;
use app\common\logic\CouponLogic;
class Goods extends ApiBase {
   
    /**
     * 商品详情页
     */
    public function goodsDetail(){
        $goodsLogic = new GoodsLogic();
        $goods_id = I("get.id/d");
        $Goods = new \app\common\model\Goods();
        $goods = $Goods::get($goods_id);
        if (empty($goods) || ($goods['is_on_sale'] == 0) || ($goods['is_virtual'] == 1 && $goods['virtual_indate'] <= time())) {
            return $this->ajaxReturn([],0,'该商品已经下架');
        }
        if (cookie('user_id')) {
            $goodsLogic->add_visit_log(cookie('user_id'), $goods);
        }
        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册
        foreach ($goods_images_list as $key => $value) {
            $goods_images_list[$key]['image_url'] = SITE_URL.$value['image_url'];
        }
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表
        $filter_spec = $goodsLogic->app_get_spec($goods_id);
        $goods['attr_group_list'] = $filter_spec;
        $goods['pic_list']        = $goods_images_list;
        $goods['goods_content']   = htmlspecialchars_decode(str_replace('/public/upload/goods', SITE_URL . '/public/upload/goods', $goods['goods_content']));
        // $freight_free = tpCache('shopping.freight_free'); // 全场满多少免运费
        $spec_goods_price = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,item_id,price,store_count,market_price"); // 规格 对应 价格 库存表
        M('Goods')->where("goods_id", $goods_id)->save(array('click_count' => $goods['click_count'] + 1)); //统计点击数

        return $this->ajaxReturn($goods);
        
    }

    public function goodsAttrInfo(){
        $goods_id = I("get.id/d");
        $attrList = I("get.attr_list");
        $key = json_decode($attrList,true);
        $key = implode('_',$key);
        $Goods = new \app\common\model\Goods();
        $goods = $Goods::get($goods_id);
        if (empty($goods) || ($goods['is_on_sale'] == 0) || ($goods['is_virtual'] == 1 && $goods['virtual_indate'] <= time())) {
            return $this->ajaxReturn([],0,'该商品已经下架');
        }

        $where['goods_id'] = $goods_id;
        $where['key']      = $key;
        $spec_goods_price  = M('spec_goods_price')->where($where)->field("key,item_id,price,store_count,market_price")->find();
        return $this->ajaxReturn($spec_goods_price);
    }

    //src=" + 头部加服务器地址
    public function addHttps($description){
        $https = SITE_URL;

        $arr_src = explode('src=',$description);
        //print_r($arr_src);
        foreach($arr_src as $k=>$v){
            if($k>0) {
                $q = substr($v, 0, 1);
                if(strpos($v,$q.'http://storym.ichezd.com/')===0 || strpos($v,$q.'https://storym.ichezd.com/')===0){
                    $v = str_replace('http://storym.ichezd.com/',$https,$v);
                    $v = str_replace('https://storym.ichezd.com/',$https,$v);

                }else if(strpos($v,$q.'/uploads/')===0){
                    $v = str_replace($q.'/uploads/',$q.$https.'uploads/',$v);
                }else{

                }
                //$v = trim($v, $q.'/uploads/');
                //$s = substr($v, 2, strpos($v,$q)-2);
                //$r = explode("/",$s);
                //$src[$r[0]][] = $r[1];
            }
            $arr_src2[] = $v;
        }
        return $im =  implode('src=',$arr_src2);
        /*if(strpos($description,'src="/')!==false){
            $description = str_replace('src="/','src="'.$https,$description);
        }
        if(strpos($description,"src='")!==false){
            $description = str_replace("src='/","src='".$https,$description);
        }
        return $description;*/
    }
   

    /**
     * [buyNow 立即购买]
     * @return [type] [description]
     */
    public function buyNow()
    {
        $uid       = I('uid', 0, 'intval');
        $goods_id  = I('goods_id', 0, 'intval');
        $goods_num = I('goods_num',0,'intval');
        $addressId = I('address_id',0,'intval');
        if ($addressId) {
            $cond['address_id'] = $addressId;
        }
        $goodsInfo = model('Common/Goods')->where(['goods_id'=>$goods_id,'is_on_sale'=>1])->find();
        if (empty($goodsInfo))  return $this->ajaxReturn([],0,'商品已下架');
        if (empty($goods_num))  return $this->ajaxReturn([],0,'请填写商品数量');
          
        $cond['user_id'] = $this->user_id;
        $address   = model('Common/UserAddress')->where($cond)->order('is_default DESC')->limit(0,1)->select();
        $defaultAddress = [];
        if ($address) {
            $defaultAddress['name']          = $address[0]['consignee'];
            $defaultAddress['province_name'] = $address[0]['province_name'];
            $defaultAddress['city_name']     = $address[0]['city_name'];
            $defaultAddress['district_name'] = $address[0]['district_name'];
            $defaultAddress['mobile']        = $address[0]['mobile'];
            $defaultAddress['detail']        = $address[0]['address'];
            $defaultAddress['address_id']    = $address[0]['address_id'];
        }
        $data = [
            'goods_id'     => $goods_id,
            'goods_name'   => $goodsInfo['goods_name'],
            'market_price' => $goodsInfo['market_price'],
            'goods_price'  => $goodsInfo['shop_price'],
            'goods_num'    => $goods_num, // 购买数量
            'original_img' => SITE_URL.$goodsInfo['original_img'],
            'address'      => $defaultAddress,
        ];
        return $this->ajaxReturn($data);
    }

    public function submit(){
        $data = I('post.');
        $goods = $this->check_virtual_goods();
        $CartLogic = new OrderLogic();
        $goods_price = $goods['shop_price']*$goods['goods_num'];
        $isbuyWhere = [
            'og.goods_id'=>$data['goods_id'],
            'o.user_id'=>$this->user_id,
            'o.deleted'=>0,
            'o.order_status'=>['neq',3]
        ];
        $isbuy = M('order_goods')->alias('og')
            ->join(C('DB_PREFIX').'order o','og.order_id = o.order_id','LEFT')
            ->where($isbuyWhere)
            ->sum('og.goods_num');
        if(($goods['goods_num']+$isbuy)>$goods['virtual_limit'] && $goods['virtual_limit']>0){
            $this->ajaxReturn([],'0','您已超过该商品的限制购买数');
        }
        $address = model('Common/UserAddress')->where(['address_id'=>$data['address_id'],'user_id'=>$this->user_id])->find();
        $data['consignee'] = $address['consignee']?$address['consignee']:$this->user['nickname'];
        $orderArr = array('user_id'=>$this->user_id,'mobile'=>$address['mobile'],'user_note'=>$data['user_note']?:"",
                'order_sn'=>$CartLogic->get_order_sn(),'goods_price'=>$goods_price,'consignee'=>$data['consignee'],
                'prom_type'=>1,'add_time'=>time(),'province'=>$address['province'],'city'=>$address['city'],'district'=>$address['district'],'address'=>$address['address'],'twon'=>$address['twon'],
                'order_amount'=>$goods_price,'total_amount'=>$goods_price,'shipping_time'=>$goods['virtual_indate']//有效期限
        );
        $order_id = M('order')->add($orderArr);
    
        $data2['order_id'] = $order_id; // 订单id
        $data2['goods_id']           = $goods['goods_id']; // 商品id
        $data2['goods_name']         = $goods['goods_name']; // 商品名称
        $data2['goods_sn']           = $goods['goods_sn']; // 商品货号
        $data2['goods_num']          = $goods['goods_num']; // 购买数量
        $data2['market_price']       = $goods['market_price']; // 市场价
        $data2['goods_price']        = $goods['shop_price']; // 商品价
        $data2['spec_key']           = $goods['goods_spec_key']; // 商品规格
        $data2['spec_key_name']      = $goods['spec_key_name']; // 商品规格名称
        $data2['sku']                = $goods['sku']; // 商品条码
        $data2['final_price']        = $goods['goods_num']*$goods['shop_price'];
        $data2['member_goods_price'] = $goods['shop_price']; // 会员折扣价
        $data2['cost_price']         = $goods['cost_price']; // 成本价
        $data2['give_integral']      = $goods['give_integral']; // 购买商品赠送积分
        $data2['prom_type']          = $goods['prom_type']; // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
        $order_goods_id              = M("OrderGoods")->add($data2);

        if($order_goods_id){
            $reduce = tpCache('shopping.reduce');
            if($reduce== 1 || empty($reduce)){
                $order = Db::name('order')->where(['order_id'=>$order_id])->find();
                minus_stock($order);//下单减库存
            }
         // if(file_exists(APP_PATH.'Common/Logic/DistributLogic.class.php'))
         // {
         //     //分销开关全局
         //     $order = M("Order")->where(array('order_id' => $order_id))->find();
         //     $distributLogic = new \Common\Logic\DistributLogic();
         //     $distributLogic->rebate_log($order); // 生成分成记录
         // }
         // $this->redirect(U('Virtual/buy_step2',array('order_id'=>$order_id)));
            $this->ajaxReturn(['order_id'=>$order_id]);
        }else{
            $this->ajaxReturn([],0,'下单失败');
        }
    }

    public function check_virtual_goods(){
        $goods_id = I('id/d');
        if(empty($goods_id))$this->error('请求参数错误');
        $goods = M('goods')->where(array('goods_id'=>$goods_id))->find();
        if(!$goods)$this->error('该商品不允许购买，原因有：商品下架、不存在、过期等');
        // if($goods['is_virtual'] == 1 && $goods['virtual_indate']>time() && $goods['store_count']>0){
        if($goods){
            $goods_num = $goods['goods_num'] = I('num/d');
            if($goods_num < 1){$this->error('最少购买1件');}
            // if ($goods['virtual_limit'] > $goods['store_count'] || $goods['virtual_limit'] == 0) {
            //     $goods['virtual_limit'] = $goods['store_count'];
            // }
            $goods_spec = I('spec/a');
            if(!empty($goods_spec) && $goods_spec !='undefined'){
                $specGoodsPriceList = M('SpecGoodsPrice')->where(array('goods_id'=>$goods_id))->cache(true,TPSHOP_CACHE_TIME)->getField("key,key_name,price,store_count,sku"); // 获取商品对应的规格价钱 库存 条码
                foreach($goods_spec as $key => $val){
                    if($val != 'undefined'){
                        $spec_item[] = $val; // 所选择的规格项
                       // $goods['spec_key_name'] .= $specGoodsPriceList[$val]['key_name'];
                    }
                }
                if(!empty($spec_item) && $spec_item !='undefined') // 有选择商品规格
                {
                    sort($spec_item);
                    $spec_key = implode('_', $spec_item);
                    if($specGoodsPriceList[$spec_key]['store_count'] < $goods_num){
                        $this->error('该商品规格库存不足');
                    }
                    $goods['goods_spec_key'] = $spec_key;
                    $goods['spec_key_name'] = $specGoodsPriceList[$spec_key]['key_name'];
                    $spec_price = $specGoodsPriceList[$spec_key]['price']; // 获取规格指定的价格
                    $goods['shop_price'] = empty($spec_price) ? $goods['shop_price'] : $spec_price;
                }
            }

            $goods_spec_key = I('goods_spec_key');
            if(!empty($goods_spec_key)){
                $specGoods = M('SpecGoodsPrice')->where(array('goods_id'=>$goods_id,'key'=>$goods_spec_key))->find();
                if($specGoods['store_count']<$goods_num)$this->error('该商品规格库存不足');
                $goods['shop_price'] = empty($specGoods['price']) ? $goods['shop_price'] : $specGoods['price'];
                $goods['goods_spec_key'] = $goods_spec_key;
                $goods['spec_key_name'] = $specGoods['key_name'];
            }
            $goods['goods_fee'] = $goods['shop_price']*$goods['goods_num'];
            return $goods;
        }else{
            $this->error('该商品不允许购买，原因可能：商品下架、不存在、过期等');
        }
    }

    /**
     * 所有商品列表
     * sort 排序规则  1,2,3,4(综合、新品、价格、销量)
     */
    public function goodsList()
    {
        $sort = input('sort', 1);
        $page = input('page', 1);
        $num = 10;
        switch($sort){
            case 1:
                $order = 'sort asc';
                break;
            case 2:
                $order = 'goods_id asc';
                break;
            case 3:
                $order = 'shop_price asc';
                break;
            case 4:
                $order = 'sales_sum desc';
                break;
        }
        $where = [];
        $list = model('Goods')->getGoodsList($where, $page, $num, $order);
        $data = [];
        if(empty($list)){
            $this->ajaxReturn($data, 0, '没有数据了');
        } else {
            foreach ($list as $k => $v) {
                $data[$k] = [
                    'name'          => $v['goods_name'],
                    'price'         => $v['shop_price'],
                    'market_price'  => $v['market_price'],
                    'original_img'  => SITE_URL.$v['original_img'],
                    'goods_id'      => $v['goods_id'],
                ];
            }
            $this->ajaxReturn($data);
        }
    }

}